package com.xinqi.utils;

import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;

/**
 * @author xin麒
 * @date 2023/2/16 22:15
 */
@Component
public class RedisIdWorker {

    private StringRedisTemplate stringRedisTemplate;
    private static final long BEGIN_TIMESTAMP = 1663619220;//项目进行商业化启动的时间戳，这里一般是从外部文件读取
    private static final int COUNT_BITS = 32;//左移位数

    public RedisIdWorker(StringRedisTemplate stringRedisTemplate) {
        this.stringRedisTemplate = stringRedisTemplate;
    }

    public long nextId(String keyPrefix){
        LocalDateTime now = LocalDateTime.now();//获取当前时间
        long nowSecond = now.toEpochSecond(ZoneOffset.UTC);//当前时间转换为long、设置ZoneOffset
        long timestamp = nowSecond - BEGIN_TIMESTAMP;//这里是代表从项目启动时到当前时间的差，也就是时间戳之差

        String date = now.format(DateTimeFormatter.ofPattern("yyyy:MM:dd"));//分类一下

        Long count = stringRedisTemplate.opsForValue().increment("irc:" + keyPrefix + ":" + date);
        //设置redis键值对的键名：key("irc:" + keyPrefix + ":" + date)-val(redis内部自增数值),键名可以自定义

        return timestamp << COUNT_BITS | count;
    }

}